iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
Software Development

用leetcode系統化學習C語言系列 第 11

指標(pointer)與動態記憶體(malloc/calloc/realloc/free)攻略-3

  • 分享至 

  • xImage
  •  

指標作為函式參數(想修改呼叫端的指標):
如果你想在函式內改變呼叫端的指標本身(例如讓呼叫端指向新 malloc 出來的記憶體),需要用 指向指標 的指標(pointer to pointer)。

範例(在函式內分配):
void allocate_array(int **p, int n) {
*p = malloc(n * sizeof **p);
if (p == NULL) { / handle error */ }
}

int main() {
int *arr = NULL;
allocate_array(&arr, 10); // 傳入 arr 的位址
// 使用 arr...
free(arr);
}


上一篇
指標(pointer)與動態記憶體(malloc/calloc/realloc/free)攻略-2
下一篇
指標(pointer)與動態記憶體(malloc/calloc/realloc/free)攻略-4
系列文
用leetcode系統化學習C語言12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言